package util;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * 网络工具类
 *
 * @author Mr.Alpaca
 * @version 1.0.0
 */
public class NetUtil {
    /**
     * 分配套接字
     *
     * @return 套接字, 若分配失败则返回null
     */
    public static DatagramSocket allocateUserSocket() {
        try {
            return new DatagramSocket();
        } catch (SocketException e) {
            System.out.println(e.getMessage());
        }
        return null;
    }

    /**
     * 发送消息到指定网址端口
     *
     * @param message 消息
     * @param address 网络地址
     * @param port    端口
     * @throws IOException 异常
     */
    public static void sendMessage(String message, InetAddress address, int port) throws IOException {
        DatagramSocket socket = new DatagramSocket();
        DatagramPacket packet = new DatagramPacket(message.getBytes(), message.getBytes().length,
                address, port);
        socket.send(packet);
        socket.close();
    }

    /**
     * 获取发往Socket的消息
     *
     * @param socket 套接字
     * @return 消息内容
     * @throws IOException 异常
     */
    public static String receiveMessage(DatagramSocket socket) throws IOException {
        byte[] contentBytes = new byte[1024];
        DatagramPacket packet = new DatagramPacket(contentBytes, contentBytes.length);
        socket.receive(packet);
        byte[] data = packet.getData();
        return new String(data, 0, packet.getLength());
    }
}
